﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.IO;

namespace MS.InformationManagement.BLL.ContactsManager
{
    public class BaseContactsAction<C>
        where C: Contactos
    {

        #region fields

        C _contact;

        #endregion

        #region Constructors

        public BaseContactsAction(C contact) { _contact = contact; }
        public BaseContactsAction() {}

        #endregion

        #region Public Methods

        public void AddContact()
        {
            if (contactExistsNew())
                throw new Exception(ExceptionConstants.ERROR_ITEM_EXISTS);
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                dc.ContactosExternos.InsertOnSubmit(_contact);
                dc.SubmitChanges();
            }
        }

        public void UpdateContact()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                dc.ContactosExternos.Attach(_contact);
                dc.SubmitChanges();
            }
        }

        public C GetContact(int contactId)
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var contact = (from item in dc.ContactosExternos
                               where item.Id == contactId
                               select item).FirstOrDefault();
                return contact as C;
            }            
        }

        #endregion

        #region Private Methods

        public bool contactExistsNew()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var contact = (from cont in dc.ContactosExternos
                               where cont.ID == _contact.ID
                               select cont).FirstOrDefault();
                return contact != null;
            }
        }

        public bool contactExistsUpdate()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var contact = (from cont in dc.ContactosExternos
                               where cont.ID == _contact.ID
                               select cont);
                return contact.Count() > 1;
            }
        }


        #endregion
    }
}
